<?php

class Platform_Factory_Abstract implements Platform_Interface, Platform_Factory_Interface
{
	private $_class_extend = array();
	
	public function retool( $prototype, $my_implementation ){
		/* it seems we must create an instance of an object to inspect it */
		$proto = $this->create( $prototype, false );
		$mine = $this->create( $my_implementation, false );
		
		/* make sure our new class implements all of the required interfaces */
		$my_class_implements = class_implements( $mine );
		foreach( class_implements( $proto ) as $iface ){
			/* does note implement this interface */
			if( !in_array( $iface, $my_class_implements ) ){
				throw new Platform_Factory_Exception('cannot retool ' . $prototype .': ' . $my_implementation . ' does not implement ' . $iface );
			}
			else {
				error_log("Platnik Class " . $my_implementation . " implements " . $iface);
			}
		}
		
		/* replace the prototype class with my version */
		$this->_class_extend[ $prototype ] = $my_implementation;
		return true;	
	}
	
	
	public function is_loaded( $name ){
		if( isset( $this->_class_extend[ $name ] ) ){
			class_exists( $this->_class_extend[ $name ] );
		}
		else {
			return false;
		} 
	}
	
	
	public function construct( $name ){
		/* if class is loaded just return an instance */
		if( $this->is_loaded( $name ) ){
			return $this->create( $name );
		}
		/* register this class as itself and return an instance */
		else {
			$this->retool( $name, $name );
			return $this->create( $name );
			
		}
	}
	

	public function create( $name, $extend = true ){
		/* if extending rules are in effect then use extension table */
		if( $extend ){
			return new $this->_class_extend[ $name ];
		}
		/* else load precisely the class requested */
		else 
		{
			return new $name;
		}
		
	}
	
}
